<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox, ElTable, ElTableColumn, ElButton, ElInput, ElForm, ElFormItem, ElDialog, ElSelect, ElOption, ElPagination, ElSwitch, ElDatePicker, ElUpload, ElAvatar } from 'element-plus';
import { UploadFilled } from '@element-plus/icons-vue';

// 用户数据
const userData = ref([]);

// 搜索条件
const searchForm = reactive({
  userName: '',
  phone: '',
  status: '',
  role: ''
});

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);

// 对话框状态
const dialogVisible = ref(false);
// 编辑模式
const editMode = ref(false);
// 当前编辑的用户ID
const currentUserId = ref(null);
// 表单数据
const formData = reactive({
  userName: '',
  realName: '',
  phone: '',
  email: '',
  role: '',
  department: '',
  status: true,
  avatar: '',
  entryDate: ''
});

// 表单验证规则
const rules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在2到20个字符之间', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 1, max: 50, message: '真实姓名长度在1到50个字符之间', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
};

// 表单引用
const userFormRef = ref(null);

// 加载用户数据
const loadUserData = () => {
  // 模拟API请求，使用静态数据
  userData.value = [
    {
      id: 1,
      userName: 'admin',
      realName: '管理员',
      phone: '13800138001',
      email: 'admin@example.com',
      role: '管理员',
      department: '总经办',
      status: true,
      avatar: 'https://t7.baidu.com/it/u=3282982438,1533560791&fm=193&f=GIF',
      createTime: '2025-06-20 08:00:00',
      entryDate: '2025-01-01'
    },
    {
      id: 2,
      userName: 'zhangwei',
      realName: '张伟',
      phone: '13800138002',
      email: 'zhangwei@example.com',
      role: '销售顾问',
      department: '销售部',
      status: true,
      avatar: 'https://t7.baidu.com/it/u=3282982438,1533560791&fm=193&f=GIF',
      createTime: '2025-06-20 08:05:00',
      entryDate: '2025-01-10'
    },
    {
      id: 3,
      userName: 'lihua',
      realName: '李华',
      phone: '13800138003',
      email: 'lihua@example.com',
      role: '销售顾问',
      department: '销售部',
      status: true,
      avatar: 'https://t7.baidu.com/it/u=3282982438,1533560791&fm=193&f=GIF',
      createTime: '2025-06-20 08:10:00',
      entryDate: '2025-01-15'
    },
    {
      id: 4,
      userName: 'wangqiang',
      realName: '王强',
      phone: '13800138004',
      email: 'wangqiang@example.com',
      role: '技术讲师',
      department: '教学部',
      status: true,
      avatar: 'https://t7.baidu.com/it/u=3282982438,1533560791&fm=193&f=GIF',
      createTime: '2025-06-20 08:15:00',
      entryDate: '2025-02-01'
    },
    {
      id: 5,
      userName: 'zhaohui',
      realName: '赵辉',
      phone: '13800138005',
      email: 'zhaohui@example.com',
      role: '技术讲师',
      department: '教学部',
      status: true,
      avatar: 'https://t7.baidu.com/it/u=3282982438,1533560791&fm=193&f=GIF',
      createTime: '2025-06-20 08:20:00',
      entryDate: '2025-02-10'
    },
    {
      id: 6,
      userName: 'sunli',
      realName: '孙丽',
      phone: '13800138006',
      email: 'sunli@example.com',
      role: '客服专员',
      department: '客服部',
      status: true,
      avatar: 'https://t7.baidu.com/it/u=3282982438,1533560791&fm=193&f=GIF',
      createTime: '2025-06-20 08:25:00',
      entryDate: '2025-03-01'
    },
    {
      id: 7,
      userName: 'chenmin',
      realName: '陈敏',
      phone: '13800138007',
      email: 'chenmin@example.com',
      role: '客服专员',
      department: '客服部',
      status: true,
      avatar: 'https://t7.baidu.com/it/u=3282982438,1533560791&fm=193&f=GIF',
      createTime: '2025-06-20 08:30:00',
      entryDate: '2025-03-15'
    },
    {
      id: 8,
      userName: 'zhoujie',
      realName: '周杰',
      phone: '13800138008',
      email: 'zhoujie@example.com',
      role: '运营专员',
      department: '运营部',
      status: true,
      avatar: 'https://t7.baidu.com/it/u=3282982438,1533560791&fm=193&f=GIF',
      createTime: '2025-06-20 08:35:00',
      entryDate: '2025-04-01'
    },
    {
      id: 9,
      userName: 'wuwen',
      realName: '吴文',
      phone: '13800138009',
      email: 'wuwen@example.com',
      role: '运营专员',
      department: '运营部',
      status: true,
      avatar: 'https://t7.baidu.com/it/u=3282982438,1533560791&fm=193&f=GIF',
      createTime: '2025-06-20 08:40:00',
      entryDate: '2025-04-10'
    },
    {
      id: 10,
      userName: 'huangping',
      realName: '黄平',
      phone: '13800138010',
      email: 'huangping@example.com',
      role: '财务专员',
      department: '财务部',
      status: true,
      avatar: 'https://t7.baidu.com/it/u=3282982438,1533560791&fm=193&f=GIF',
      createTime: '2025-06-20 08:45:00',
      entryDate: '2025-05-01'
    },
    {
      id: 11,
      userName: 'yangming',
      realName: '杨明',
      phone: '13800138011',
      email: 'yangming@example.com',
      role: '人事专员',
      department: '人事部',
      status: true,
      avatar: 'https://t7.baidu.com/it/u=3282982438,1533560791&fm=193&f=GIF',
      createTime: '2025-06-20 08:50:00',
      entryDate: '2025-05-15'
    }
  ];
};

// 计算总数
const total = computed(() => userData.value.length);

// 计算当前页显示的数据
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + Number(pageSize.value);
  return userData.value.slice(start, end);
});

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
};

// 重置搜索条件
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = '';
  });
  currentPage.value = 1;
};

// 处理分页
const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

// 切换用户状态
const toggleUserStatus = (row) => {
  const newStatus = !row.status;
  ElMessageBox.confirm(
    `确定要将用户"${row.realName}"${newStatus ? '启用' : '禁用'}吗？`,
    '状态变更确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    row.status = newStatus;
    ElMessage.success(newStatus ? '用户已启用' : '用户已禁用');
  }).catch(() => {
    // 取消状态变更，需要恢复原状态（因为switch组件已经改变了值）
    row.status = !newStatus;
  });
};

// 打开添加对话框
const openAddDialog = () => {
  editMode.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (row) => {
  editMode.value = true;
  currentUserId.value = row.id;
  Object.assign(formData, row);
  dialogVisible.value = true;
};

// 删除用户
const deleteUser = (row) => {
  if (row.userName === 'admin') {
    ElMessage.warning('管理员账户不能删除');
    return;
  }
  
  ElMessageBox.confirm('确定要删除该用户吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = userData.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      userData.value.splice(index, 1);
      ElMessage.success('删除成功');
    }
  }).catch(() => {
    // 取消删除
  });
};

// 重置密码
const resetPassword = (row) => {
  ElMessageBox.confirm(
    `确定要将用户"${row.realName}"的密码重置为"123456"吗？`,
    '重置密码确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('密码重置成功，新密码：123456');
  }).catch(() => {
    // 取消重置
  });
};

// 保存用户
const saveUser = () => {
  userFormRef.value.validate((valid) => {
    if (valid) {
      const now = new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).replace(/\//g, '-');
      
      if (editMode.value) {
        // 编辑模式
        const index = userData.value.findIndex(item => item.id === currentUserId.value);
        if (index !== -1) {
          Object.assign(userData.value[index], formData);
          ElMessage.success('编辑成功');
        }
      } else {
        // 添加模式
        const newUser = {
          id: Date.now(), // 模拟生成唯一ID
          ...formData,
          createTime: now
        };
        userData.value.push(newUser);
        ElMessage.success('添加成功');
      }
      dialogVisible.value = false;
      resetForm();
    }
  });
};

// 上传头像
const handleAvatarUpload = (file) => {
  // 模拟上传，实际项目中需要调用后端API
  const reader = new FileReader();
  reader.readAsDataURL(file.raw);
  reader.onload = (e) => {
    formData.avatar = e.target.result;
  };
  return false; // 阻止默认上传行为
};

// 重置表单
const resetForm = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields();
  }
  Object.keys(formData).forEach(key => {
    formData[key] = '';
  });
  formData.status = true;
  currentUserId.value = null;
};

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false;
  resetForm();
};

// 组件挂载时加载数据
onMounted(() => {
  loadUserData();
});
</script>

<template>
  <div class="user-container">
    <div class="search-bar">
      <div class="search-item">
        <label>用户名</label>
        <ElInput v-model="searchForm.userName" placeholder="请输入" style="width: 150px;"></ElInput>
      </div>
      <div class="search-item">
        <label>手机号</label>
        <ElInput v-model="searchForm.phone" placeholder="请输入" style="width: 150px;"></ElInput>
      </div>
      <div class="search-item">
        <label>用户状态</label>
        <ElSelect v-model="searchForm.status" placeholder="请选择" style="width: 120px;">
          <ElOption label="启用" value="true"></ElOption>
          <ElOption label="禁用" value="false"></ElOption>
        </ElSelect>
      </div>
      <div class="search-item">
        <label>用户角色</label>
        <ElSelect v-model="searchForm.role" placeholder="请选择" style="width: 150px;">
          <ElOption label="管理员" value="管理员"></ElOption>
          <ElOption label="销售顾问" value="销售顾问"></ElOption>
          <ElOption label="技术讲师" value="技术讲师"></ElOption>
          <ElOption label="客服专员" value="客服专员"></ElOption>
          <ElOption label="运营专员" value="运营专员"></ElOption>
          <ElOption label="财务专员" value="财务专员"></ElOption>
          <ElOption label="人事专员" value="人事专员"></ElOption>
        </ElSelect>
      </div>
      <ElButton type="primary" @click="handleSearch">搜索</ElButton>
      <ElButton @click="handleReset">重置</ElButton>
    </div>
    
    <div class="user-header">
      <ElButton type="primary" @click="openAddDialog">+ 新增用户</ElButton>
    </div>
    
    <div class="user-content">
      <ElTable 
        v-if="userData.length > 0"
        :data="currentPageData" 
        style="width: 100%; height: calc(100% - 60px);"
        stripe
        border
        fit
      >
        <ElTableColumn type="index" label="序号" min-width="80"></ElTableColumn>
        <ElTableColumn 
          prop="avatar" 
          label="头像" 
          min-width="100"
          align="center"
        >
          <template #default="{ row }">
            <ElAvatar :src="row.avatar" size="small"></ElAvatar>
          </template>
        </ElTableColumn>
        <ElTableColumn 
          prop="userName" 
          label="用户名" 
          min-width="120"
        />
        <ElTableColumn 
          prop="realName" 
          label="真实姓名" 
          min-width="120"
        />
        <ElTableColumn 
          prop="phone" 
          label="手机号" 
          min-width="120"
        />
        <ElTableColumn 
          prop="email" 
          label="邮箱" 
          min-width="180"
        />
        <ElTableColumn 
          prop="role" 
          label="角色" 
          min-width="120"
        />
        <ElTableColumn 
          prop="department" 
          label="所属部门" 
          min-width="120"
        />
        <ElTableColumn 
          prop="entryDate" 
          label="入职日期" 
          min-width="120"
        />
        <ElTableColumn 
          prop="status" 
          label="用户状态" 
          min-width="100"
          align="center"
        >
          <template #default="{ row }">
            <ElSwitch
              v-model="row.status"
              @change="toggleUserStatus(row)"
              active-color="#13ce66"
              inactive-color="#ccc"
              :disabled="row.userName === 'admin'"
            ></ElSwitch>
          </template>
        </ElTableColumn>
        <ElTableColumn 
          prop="createTime" 
          label="创建时间" 
          min-width="180"
        />
        <ElTableColumn 
          label="操作" 
          min-width="180" 
          fixed="right"
        >
          <template #default="{ row }">
            <div class="action-buttons">
              <ElButton 
                type="text" 
                @click="openEditDialog(row)"
                size="small" 
                style="color: #409EFF;"
                :disabled="row.userName === 'admin'"
              >
                修改
              </ElButton>
              <ElButton 
                type="text" 
                @click="resetPassword(row)"
                size="small" 
                style="color: #67C23A;"
              >
                重置密码
              </ElButton>
              <ElButton 
                type="text" 
                @click="deleteUser(row)"
                size="small" 
                style="color: #F56C6C;"
                :disabled="row.userName === 'admin'"
              >
                删除
              </ElButton>
            </div>
          </template>
        </ElTableColumn>
      </ElTable>
      <div v-else class="empty-data">暂无用户数据</div>
      
      <!-- 分页组件 -->
      <div class="pagination">
        <span class="total">共 {{ total }} 条</span>
        <ElSelect v-model="pageSize" @change="handleSizeChange" style="width: 100px;">
          <ElOption label="10条/页" value="10"></ElOption>
          <ElOption label="20条/页" value="20"></ElOption>
          <ElOption label="50条/页" value="50"></ElOption>
        </ElSelect>
        <ElPagination
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          layout="prev, pager, next, jumper"
        ></ElPagination>
      </div>
    </div>
    
    <!-- 添加/编辑用户对话框 -->
    <ElDialog
      :title="editMode ? '编辑用户' : '新增用户'"
      v-model="dialogVisible"
      width="600px"
      @close="closeDialog"
    >
      <ElForm
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
      >
        <ElFormItem label="头像">
          <ElUpload
            :file-list="[]"
            :auto-upload="false"
            :on-change="handleAvatarUpload"
            :show-file-list="false"
            style="display: inline-block;"
          >
            <ElAvatar :src="formData.avatar || 'https://t7.baidu.com/it/u=3282982438,1533560791&fm=193&f=GIF'" size="medium">
              <UploadFilled v-if="!formData.avatar" />
            </ElAvatar>
          </ElUpload>
          <div class="upload-tip">点击头像上传</div>
        </ElFormItem>
        <ElFormItem label="用户名" prop="userName">
          <ElInput v-model="formData.userName" :disabled="editMode" placeholder="请输入用户名" />
        </ElFormItem>
        <ElFormItem label="真实姓名" prop="realName">
          <ElInput v-model="formData.realName" placeholder="请输入真实姓名" />
        </ElFormItem>
        <ElFormItem label="手机号" prop="phone">
          <ElInput v-model="formData.phone" placeholder="请输入手机号" />
        </ElFormItem>
        <ElFormItem label="邮箱" prop="email">
          <ElInput v-model="formData.email" placeholder="请输入邮箱" />
        </ElFormItem>
        <ElFormItem label="用户角色" prop="role">
          <ElSelect v-model="formData.role" placeholder="请选择">
            <ElOption label="管理员" value="管理员"></ElOption>
            <ElOption label="销售顾问" value="销售顾问"></ElOption>
            <ElOption label="技术讲师" value="技术讲师"></ElOption>
            <ElOption label="客服专员" value="客服专员"></ElOption>
            <ElOption label="运营专员" value="运营专员"></ElOption>
            <ElOption label="财务专员" value="财务专员"></ElOption>
            <ElOption label="人事专员" value="人事专员"></ElOption>
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="所属部门">
          <ElSelect v-model="formData.department" placeholder="请选择">
            <ElOption label="总经办" value="总经办"></ElOption>
            <ElOption label="销售部" value="销售部"></ElOption>
            <ElOption label="教学部" value="教学部"></ElOption>
            <ElOption label="客服部" value="客服部"></ElOption>
            <ElOption label="运营部" value="运营部"></ElOption>
            <ElOption label="财务部" value="财务部"></ElOption>
            <ElOption label="人事部" value="人事部"></ElOption>
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="入职日期">
          <ElDatePicker
            v-model="formData.entryDate"
            type="date"
            placeholder="请选择入职日期"
            style="width: 100%;"
          />
        </ElFormItem>
        <ElFormItem label="用户状态">
          <ElSwitch v-model="formData.status" active-color="#13ce66" inactive-color="#ccc"></ElSwitch>
        </ElFormItem>
      </ElForm>
      
      <template #footer>
        <ElButton @click="closeDialog">取消</ElButton>
        <ElButton type="primary" @click="saveUser">确定</ElButton>
      </template>
    </ElDialog>
  </div>
</template>

<style scoped>
/* 确保body没有默认margin */
:global(body) {
  margin: 0;
  padding: 0;
}

.user-container {
  padding: 15px;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  box-sizing: border-box;
}

/* 搜索栏样式 */
.search-bar {
  background: #fff;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-item label {
  white-space: nowrap;
  font-weight: 500;
  color: #606266;
}

.user-header {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 15px;
}

.user-content {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  width: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.empty-data {
  text-align: center;
  padding: 100px 0;
  color: #999;
  font-size: 16px;
}

/* 自定义表格样式 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  width: 100%;
}

:deep(.el-table__header th) {
  background-color: #fafafa;
  font-weight: 600;
  color: #333;
  padding: 15px 0;
}

:deep(.el-table__body tr:hover > td) {
  background-color: #f5f7fa;
}

:deep(.el-table__row) {
  height: 60px;
}

:deep(.el-button--small) {
  padding: 8px 16px;
}

/* 头像上传提示 */
.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
  gap: 15px;
  flex-shrink: 0;
}

.pagination .total {
  color: #606266;
}

.action-buttons {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

/* 操作按钮样式 */
:deep(.el-button--text) {
  padding: 8px 10px;
}

:deep(.el-button.is-disabled.is-text) {
  color: #c0c4cc !important;
  cursor: not-allowed;
}
</style>